﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using System.Web.Mvc.Html;
using System.Web;

namespace Kooboo.Commerce.AddIn
{
    public static class ValidationExtensions
    {
        public static MvcHtmlString EnableWebControlClientValidation(this HtmlHelper<WebControlModel> html)
        {
            FieldValidationMetadata metadata = new FieldValidationMetadata();

            var name = System.Web.HttpUtility.HtmlEncode(html.ViewData.Model.Name);

            metadata.FieldName = name;
            metadata.ValidationMessageId = name + "_validationMessage";
            metadata.ReplaceValidationMessageContents = true;

            foreach (var rule in html.ViewData.Model.ProductAttribute.ValidationRules)
            {

                var item = new ModelClientValidationRule
                {
                    ValidationType = rule.Validator.Name.ToLower(),
                    ErrorMessage = rule.ErrorMessage

                };

                item.ValidationParameters.Add("view", name);

                foreach (var i in rule.Parameters)
                {
                    item.ValidationParameters.Add(i.Name, i.Value);
                }


                metadata.ValidationRules.Add(item);

            }

            if (html.ViewContext.FormContext.FieldValidators.ContainsKey(name))
            {
                html.ViewContext.FormContext.FieldValidators[name] = metadata;
            }
            else
            {
                html.ViewContext.FormContext.FieldValidators.Add(name, metadata);
            }

            return html.ValidationMessage(name);
        }
    }
}
